<?php
class Project extends CI_Controller{
    public $_indexView = "administrator/project/index";
    public $_listView  = "administrator/project/list";
    public $_addView   = "administrator/project/add";
    public $_editView  = "administrator/project/edit";
    public $_applyView = "administrator/project/applytemplate";
    public $_ajaxView = "administrator/project/list_data";
    
	public 	function __construct(){
		parent::__construct();
        $this->load->helper('url');
		$this->load->Model("administrator/Mdproject");
        $this->load->Model("administrator/Mddevice");
        $this->load->Model("administrator/Mdtemplate");
	}
    
    public function loadView($temp) {
        if(!isset($temp["data"])) $temp["data"] = '';
        $this->load->view("administrator/index",$temp);
    }
    
    
	public function index(){
	    $finished = 1;
	    $temp["template"] = $this->_listView;
		$temp["data"] = $this->Mdproject->finishedProject($finished);
		$this->loadView($temp);
        
	}
    
    public function list_data($finished=null){
	    $temp["template"] = $this->_ajaxView;
		$temp["data"] = $this->Mdproject->finishedProject($finished);
		$this->load->view("administrator/ajax",$temp);
        
        
	}
    
    
    public function add() {
        $temp["template"] = $this->_addView;
        
        if(isset($_POST['ok'])) {
            $dataPost = $this->input->post();
            if($this->Mdproject->addProject($dataPost)) 
                $this->session->set_flashdata('success', "Insert successfully!");
            else 
                $this->session->set_flashdata('error', "Insert error!");
            redirect(base_url().$this->_indexView);
        }
        $this->loadView($temp);
    }
    
    public function edit($id) {
        $temp["template"] = $this->_editView;
        if(isset($_POST['ok'])) {
            $dataPost = $this->input->post();
            if($this->Mdproject->updateProject($dataPost, $id)) 
                $this->session->set_flashdata('success', "Update successfully!");
            else 
                $this->session->set_flashdata('error', "Update error!");
            redirect(base_url().$this->_editView.'/'.$id);
            //redirect(base_url().$this->_indexView);
        }
        $temp["data"] = $this->Mdproject->getProject($id);
        $this->loadView($temp);
    }
    
    public function delete($id) {
        if($this->Mdproject->deleteProject($id)) 
            $this->session->set_flashdata('success', "Delete successfully!");
        else 
            $this->session->set_flashdata('error', "Delete error!");
        redirect(base_url().$this->_indexView);
    }
    
    public function export($id) {
        $PROJ = $this->Mdproject->getProject($id);
        $devices = $this->Mddevice->allDevice();
        foreach($devices as $k=>$v) {
            $path = "/tmp/".$v['d_name'];
            if (!is_dir($path)) {
                @mkdir($path);
            }
            $this->exportForDevice($PROJ, $v, $path);
        }
        $this->session->set_flashdata('success', "Export successfully!");
        redirect(base_url().$this->_indexView);
    }
    
    public function apply() {
        $temp["template"] = $this->_applyView;
		$temp["data"] = $this->Mdtemplate->listTemplate();
        
        if(isset($_POST['ok'])) {
            $templateData = $this->Mdtemplate->templateById($_POST['template_id']);
            echo "<pre>";
            print_r($this->input->post());
            echo "</pre>";
        }
        else {
            $this->loadView($temp);
        }
    }
    
    public function exportForDevice($PROJ, $DEV, $PATH) {
        $background = "#FFFFFF";
        try
        {
            /***** TOP ******/
            $im = new Imagick();
    
            if($PROJ[ 'TB_bckGrad1' ])
            {
		        $im->newImage($DEV[ 'd_width' ], $DEV[ 'd_topHeight' ], $background, "png");
		        $gradient = new Imagick();
		        $gradient->newPseudoImage($DEV[ 'd_width' ], $DEV[ 'd_topHeight' ], "gradient:".$this->rgb2hex($PROJ[ 'TB_bckGrad1' ])."-".$this->rgb2hex($PROJ[ 'TB_bckGrad2' ]));
		        $im->compositeImage( $gradient, imagick::COMPOSITE_OVER, 0, 0 );
            }
            elseif($PROJ[ 'TB_bckImg' ])
            {
		        $imageBackground = new Imagick("/".$PROJ[ 'TB_bckImg' ]);
                $im->newImage( $DEV[ 'd_width' ], $DEV[ 'd_topHeight' ], $background, "png" );
                $this->createBackgroundForImage($im, $imageBackground);
            }
            elseif($PROJ[ 'TB_bckCol' ]) 
            {
                $im->newImage( $DEV[ 'd_width' ], $DEV[ 'd_topHeight' ], $PROJ[ 'TB_bckCol' ], "png" );
            }
    
            if($PROJ[ 'TB_logoImg' ])
            {
                $imageLogo = new Imagick('/'.$PROJ[ 'TB_logoImg' ]);
        
                $left = $DEV[ 'd_logoPadding' ];
                $top = ($im->getImageHeight() - $imageLogo->getImageHeight()) / 2;
                if($PROJ[ 'TB_logo_align' ])
                {
                    switch ($PROJ[ 'TB_logo_align' ])
                    {
            	        case "left":
                            break;
                        case "center":
                            $left = ($im->getImageWidth() - $imageLogo->getImageWidth()) / 2;
                            break;
                        case "right":
                            $left = $im->getImageWidth() - $imageLogo->getImageWidth() - $left;
                            break;
                    }
                }
        
                $im->compositeImage($imageLogo, Imagick::COMPOSITE_OVER, $left, $top);
            }
    
            $im->writeImage( $PATH.'/top_'.$DEV[ 'd_name'].'.png' );

    
            /***** MID ******/
            if($PROJ[ 'M_bckGrad1' ])
            {
		        $im->newImage($DEV[ 'd_width' ], $DEV[ 'd_coverHeight' ], $background, "png");
		        $gradient = new Imagick();
		        $gradient->newPseudoImage($DEV[ 'd_width' ], $DEV[ 'd_coverHeight' ], "gradient:".$this->rgb2hex($PROJ[ 'M_bckGrad1' ])."-".$this->rgb2hex($PROJ[ 'M_bckGrad2' ]));
		        $im->compositeImage( $gradient, imagick::COMPOSITE_OVER, 0, 0 );
            }
            elseif($PROJ[ 'M_bckImg' ])
            {
                $imageBackground = new Imagick("/".$PROJ[ 'M_bckImg' ]);
                $im->newImage( $DEV[ 'd_width' ], $DEV[ 'd_coverHeight' ], $background, "png" );
                $this->createBackgroundForImage($im, $imageBackground);
            }
            elseif($PROJ[ 'M_bckCol' ]) 
            {
                $im->newImage( $DEV[ 'd_width' ], $DEV[ 'd_coverHeight' ], $PROJ[ 'M_bckCol' ], "png" );
            }
    
            $imagickDraw = new ImagickDraw();
            //$imagickDraw->composite
            $im->writeImage( $PATH.'/cover_'.$DEV[ 'd_name'].'.png' );
    
    
            /***** BOTTOM ******/
            if($PROJ[ 'BB_bckGrad1' ])
            {
		        $im->newImage($DEV[ 'd_width' ], $DEV[ 'd_bottomHeight' ], $background, "png");
		        $gradient = new Imagick();
		        $gradient->newPseudoImage($DEV[ 'd_width' ], $DEV[ 'd_bottomHeight' ], "gradient:".$this->rgb2hex($PROJ[ 'BB_bckGrad1' ])."-".$this->rgb2hex($PROJ[ 'BB_bckGrad2' ]));
		        $im->compositeImage( $gradient, imagick::COMPOSITE_OVER, 0, 0 );
            }
            elseif($PROJ[ 'BB_bckImg' ])
            {
                $imageBackground = new Imagick("/".$PROJ[ 'BB_bckImg' ]);
                $im->newImage( $DEV[ 'd_width' ], $DEV[ 'd_bottomHeight' ], $background, "png" );
                $this->createBackgroundForImage($im, $imageBackground);
            }
            elseif($PROJ[ 'BB_bckCol' ]) 
            {
                $im->newImage( $DEV[ 'd_width' ], $DEV[ 'd_bottomHeight' ], $PROJ[ 'BB_bckCol' ], "png" );
            }
    
            $imagickDraw = new ImagickDraw();
            //$imagickDraw->composite
            $im->writeImage( $PATH.'/bottom_'.$DEV[ 'd_name'].'.png' );
    
            /***** BUTTONS ******/
            if($PROJ[ 'BB_RefButImg' ])
            {
                $im = new Imagick("/".$PROJ[ 'BB_RefButImg' ]);
                $im->writeImage( $PATH.'/refBut_'.$DEV[ 'd_name'].'.png' );
            }
            if($PROJ[ 'BB_dlButImg' ])
            {
                $im = new Imagick("/".$PROJ[ 'BB_dlButImg' ]);
                $im->writeImage( $PATH.'/dlBut_'.$DEV[ 'd_name'].'.png' );
            }
            if($PROJ[ 'BB_InfoButImg' ])
            {
                $im = new Imagick("/".$PROJ[ 'BB_InfoButImg' ]);
                $im->writeImage( $PATH.'/infoBut_'.$DEV[ 'd_name'].'.png' );
            }
        }
        catch(Exception $e)
        {
            echo $e->getMessage();
        }

    }
    
    public function createBackgroundForImage($im, $imageBackground) {
        $loopWidth = ceil($im->getImageWidth() / $imageBackground->getImageWidth());
        $loopHeight = ceil($im->getImageHeight() / $imageBackground->getImageHeight());
    
        for ($i = 0; $i < $loopHeight; $i++)
        {
            for ($j = 0; $j < $loopWidth; $j++)
            {
                $im->compositeImage($imageBackground, Imagick::COMPOSITE_OVER, ($j * $imageBackground->getImageWidth()), ($i * $imageBackground->getImageHeight()));
            }
        }
    }
    
    public function rgb2hex($str) {
        $arr = explode(")", $str);
        $rgb = $arr[0];
        //echo $rgb, "<br/>";
        $arr = explode(",", substr($rgb, 4, strlen($rgb)-1));
	
	    $hex = "#";
	    $hex .= str_pad(dechex($arr[0]), 2, "0", STR_PAD_LEFT);
	    $hex .= str_pad(dechex($arr[1]), 2, "0", STR_PAD_LEFT);
	    $hex .= str_pad(dechex($arr[2]), 2, "0", STR_PAD_LEFT);
    
        //echo $hex, "<br/>";

	    return $hex; // returns the hex value including the number sign (#)
    }
} 